<?php

namespace app\Modules\Api\controllers;



use app\Modules\Api\models\User;
use app\Modules\Api\models\Sign;
use app\filters\Json;
use app\helpers\Request;
use app\Modules\Api\models\Bill;


/**
 * Class SignController
 * @package app\Modules\Api\controllers
 */
class SignController extends ControllerBase
{
    /**
     * 签到列表
     * @return array
     */
    public function actionIndex()
    {
        $user_id = Request::strictpost('user_id','缺少用户id');

        $user = User::findOne($user_id);
        if(!$user)
            return Json::error('用户未找到');

        $continuity = Sign::getContinuity($user_id);
        $can_sign = $continuity === false?'0':'1';
        $take_money = Sign::getTakeMoney($continuity);
        $query = Sign::find()->where(['user_id'=>$user_id]);
        /** @var  $signs Sign[]*/
        $signs = $query->orderBy(['created_at'=>SORT_DESC])->limit(30)->all();
        $get_take_money = $query->sum('take_money');
        $data = [
            'today'=>[
                'can_sign'=>$can_sign,
                'take_money'=>$continuity===false?strval($signs[0]->take_money):strval($take_money),
            ],
            'signs'=>$signs,
            'get_take_money'=>$get_take_money?strval($get_take_money):'0',
        ];


        return Json::success($data);
    }

    /**
     * 添加签到
     * @return array
     */
    public  function actionCreate()
    {
        $user_id = Request::strictpost('user_id','缺少用户id');

        $user = User::findOne($user_id);
        if(!$user)
            return Json::error('用户未找到');

        $continuity = Sign::getContinuity($user_id);
        if($continuity === false)
            return Json::error('用户签到过');


        $take_money = Sign::getTakeMoney($continuity);
        $sign = new Sign();
        $sign->continuity = $continuity+1;
        $sign->take_money = $take_money;
        $sign->user_id = $user_id;
        $sign->save(false);

        $user->give_money += $take_money;
        $user->save(false);
        Bill::log('签到',$take_money,$user->userid);
        return Json::success($user);
    }
}